#include "FTBitmapChar.h"
#include "GLCallBatcher.h"
#include "ftglyph.h"
#include <assert.h>
#include "freetype.h"


FTBitmapChar::FTBitmapChar() {
	x           = 0;
	y           = 0;
	width       = 0;
	height      = 0;
	xOffset     = 0;
	yOffset     = 0;
	xAdvance    = 0;
	glyph       = NULL;
}

FTBitmapChar::~FTBitmapChar() {
	x           = 0;
	y           = 0;
	width       = 0;
	height      = 0;
	xOffset     = 0;
	yOffset     = 0;
	xAdvance    = 0;
	glyph       = NULL;
}

	

void FTBitmapChar::initTexCoords(int texWidth, int texHeight) {
	float x1 = (float)x/(float)texWidth;
   	float y1 = (float)y/(float)texHeight;
	float x2 = (float)(x+width)/(float)texWidth;
  	float y2 = (float)(y+height)/(float)texHeight;

	texCoords[0] = x1;
	texCoords[1] = y1;

	texCoords[2] = x2;
	texCoords[3] = y1;

	texCoords[4] = x1;
	texCoords[5] = y2;

	texCoords[6] = x2;
	texCoords[7] = y2;
}

// setup quad and draw as triangle groups
void FTBitmapChar::render(int x, int y, float scale, GLCallBatcher *glCallBatcher) const {
	if (isEmpty())
        return;
    
    assert(height > 0 && width > 0);
    
	x += xOffset * scale;
	y += yOffset * scale;
    
	float vertices[verticesPerQuad*compVertPos];
    
	vertices[0] = (float)x;
	vertices[1] = (float)y;
    
	vertices[2] = (float)(x+width*scale);
	vertices[3] = (float)y;
    
	vertices[4] = (float)x;
	vertices[5] = (float)(y-height*scale);

	vertices[6] = (float)(x+width*scale);
	vertices[7] = (float)(y-height*scale);

	glCallBatcher->addQuad(texCoords, vertices);
} 


void FTBitmapChar::drawToBitmap(unsigned char* pData, int texWidth, int texHeight) {
	if (isEmpty()) return;
	initTexCoords(texWidth, texHeight);
	// Convert The Glyph To A Bitmap.
	FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
	FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph;

	// This Reference Will Make Accessing The Bitmap Easier.
	FT_Bitmap& bitmap = bitmap_glyph->bitmap;

	assert(bitmap.width == width);
	assert(bitmap.rows == height);
	int x, y = 0;
	int index;
	for (y = 0; y < bitmap.rows; y++) {
		for (x = 0; x < bitmap.width; x++) {
			index = (this->y + y)* texWidth + this->x + x;
			pData[index] = bitmap.buffer[y * bitmap.width + x];
		}
	}
}

void FTBitmapChar::releaseGlyph() {
	if (glyph)
        FT_Done_Glyph(glyph);
}
